<?php

class Milestone extends Node
{

    static protected $currentUserId;
    //id, resource, logo
    protected $title;
    protected $description;
    //protected $project_name;//?? en caso que fuera projecto esto sería el titulo
    //en caso de no ser projecto necesitamos saber cual es el projecto?
    protected $owner;
    protected $owner_name;
    protected $iam_owner;
    protected $project;
    protected $privacy_project;
    protected $main_milestone;
    protected $privacy_milestone;
    //protected $parent_milestone;
    protected $trace;
    protected $closed;
    protected $cerrada;
    protected $creada;
    protected $actualizada;
    protected $num_childs;
    protected $num_encloseds;
    protected $votes_plus;
    protected $votes_minus;
    protected $expanded = false;
    protected $editting = false;
    protected $attaching = false;
    protected $editable = false; //si soy el propietario
    protected $voteable = false; //si no soy el propietario y no lo he votado ya;
    protected $replyable = false;
    protected $levelable = false;
    protected $closeable = false;
    protected $deletable = false;
    protected $enclosable = false;
    protected $unclosable = false;

    function __construct()
    {
        $this->iam_owner = (self::$currentUserId == $this->owner);
        $this->editable = $this->iam_owner && $this->closed == 'N';
        $this->replyable = ( $this->closed == 'N' );
        //en principio no puede votar
        //$this->voteable=false;
    }

    function handleGET( Event $e )
    {
        if ( $e->tag == 'expand' ) {

            $this->_setExpanded( !$this->expanded );
            $e->cancelBubble();
        }
        if ( $e->tag == 'attach' ) {

            if ( $this->enclosable ) $this->_setAttaching( !$this->attaching );

            $e->cancelBubble();
        }
        else if ( $e->tag == 'edit' ) {
            if ( $this->editable ) $this->_setEditting( !$this->editting );

            $e->cancelBubble();
        }
    }

    function setExpanded( $expanded )
    {
        $this->expanded = $expanded;
    }

    function setEditting( $editting )
    {
        $this->editting = $editting;
    }

    function setAttaching( $attaching )
    {
        $this->attaching = $attaching;
    }

    function doPOST( Event $e )
    {
        if ( $e->tag == 'reply' ) {


            if ( $this->replyable && !empty( $_POST[ 'description' ] ) ) {

                $_POST[ 'description' ] = HTMLParser::parse( $_POST[ 'description' ],
                                array( 'p', 'a', 'strong', 'em', 'table', 'tbody',
                            'thead', 'tfoot', 'tr', 'th', 'td', 'ol', 'ul', 'li' ) );

                $sql = 'UPDATE milestones SET updated=NOW(), num_childs=num_childs+1 WHERE id=' . $this->id;
                MyLink::$default->execute( $sql );

                $current_user = User::getLogged()->getId();

                $sql = 'INSERT INTO milestones ( project, main_milestone, parent_milestone, owner, description, updated, privacy_project, privacy_milestone ) VALUES (';
                $sql.=$this->project . ', ' . $this->main_milestone . ', ' . $this->id . ', ' . $current_user . ', ' . MyLink::quote( $_POST[ 'description' ] ) . ', NOW(),\'' . $this->privacy_project . '\',\'' . $this->privacy_milestone . '\' )';
                MyLink::$default->execute( $sql );

                $sql = 'UPDATE milestones SET trace=\'' . $this->trace . MyLink::$default->insert_id . '.\' WHERE id=' . MyLink::$default->insert_id;
                MyLink::$default->execute( $sql );

                $this->_setExpanded( true );

                $this->notifyOwner( 'REPLY' );


                //actualizo el main milestone tb
                if ( $this->main_milestone != $this->id ) { //informamos tb al creador de la cadena de hitos
                    $sql = 'UPDATE milestones SET updated=NOW() WHERE id=' . $this->main_milestone;
                    MyLink::$default->execute( $sql );

                    $owner = MyLink::$default->get_rows( 'SELECT owner FROM milestones WHERE id=' . $this->main_milestone,
                                    true )->getField( 0 );

                    if ( $current_user != $owner ) {

                        $sql = 'INSERT INTO notifications ( milestone, user, type, who ) VALUES (' . $this->id . ',' . $owner . ',\'REPLY_MAIN\',' . $current_user . ')';
                        MyLink::$default->execute( $sql );
                    }
                }
            }

            $e->cancelBubble();
        } else if ( $e->tag == 'edit' ) {

            if ( $this->editable && !empty( $_POST[ 'description' ] ) ) {
                //OJO COMO CONVIERTO EL COTENIDO DENTRO DE LAS ETIQUETAS EN SUS ENTIDADES HTML?????

                $_POST[ 'description' ] = HTMLParser::parse( $_POST[ 'description' ],
                                array( 'p', 'a', 'strong', 'em', 'table', 'tbody',
                            'thead', 'tfoot', 'tr', 'th', 'td', 'ol', 'ul', 'li' ) );
                $sql = 'UPDATE milestones SET updated=NOW(), description=' . MyLink::quote( $_POST[ 'description' ] ) . ' WHERE id=' . $this->id;
                MyLink::$default->execute( $sql );
            }

            $e->cancelBubble();
        } else if ( $e->tag == 'delete_enclosed' ) {
            $e->cancelBubble();
        }
    }

    function fill()
    {

        if ( $this->num_encloseds > 0 ) {
            $encloseds = array( );


            //Los enclosed no pertenecen a un único milestone
            Node::getArray( 'enclosed_milestone', $encloseds,
                    'm.milestone=' . $this->id, 'active, num' );

            foreach ( $encloseds as $e ) $this->appendChild( $e );

            //   for($i=1;$i<=$this->num_encloseds;$i++)
            //     $this->appendChild( Node::getInstance ('enclosed', array($this->id,$i) ) ); //Esto aprovecha la cache del milestone padre
        }

        if ( $this->attaching ) {

            $lista = Node::getInstance( 'enclosed_list',
                            'enclosed_milestone_list_' + $this->id );

            $lista->_setProject( $this->project );
            $lista->_setMilestoneToAttach( $this->id );
            $lista->_numPerPage( 10 );

            $this->appendChild( $lista );
        }

        if ( $this->expanded ) {
            $hijos = array( );

            Node::getArray( 'milestone', $hijos,
                    'parent_milestone=' . $this->id, 'when' );

            $milestones = array( );

            foreach ( $hijos as $h ) {
                $this->appendChild( $h );

                //     if($h->num_encloseds>0)
                //       $milestones[]=$h->getId();
            }

            //MEJOR QUE ESTO SERIA UN INNER JOIN????
            //si los obtengo aqui así, entonces tengo en el milestone tengo que obtenerlos uno por uno para aprovechar la cache
            //if(count($milestones)>0){
            //  $encloseds=array();
            //  Node::getArray('enclosed', $encloseds, 'milestone IN (' . implode(',',$milestones).')');
            //}
        }
    }

    function notifyOwner( $type )
    {
        if ( !$this->iam_owner ) {
            $sql = 'INSERT INTO notifications ( milestone, main_milestone, user, type, who ) VALUES (' . $this->id . ',' . $this->main_milestone . ',' . $this->owner . ',\'' . $type . '\',' . self::$currentUserId . ')';
            MyLink::$default->execute( $sql );
        }
    }

    static function setCurrentUserId()
    {
        self::$currentUserId = User::getLogged()->getId();
    }

}

Milestone::setCurrentUserId();
?>
